import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_channel_demo/api/worker.dart';
import 'package:flutter_channel_demo/models/worker.dart';
import 'package:flutter_channel_demo/models/organization.dart';
import 'package:flutter_channel_demo/api/send.dart';
import 'package:flutter_channel_demo/api/contracts.dart';
import 'package:flutter_channel_demo/pages/home/my_contracts_widget.dart';
import 'package:flutter_channel_demo/pages/home/my_info_widget.dart';
import 'package:flutter_channel_demo/pages/home/my_work_widget.dart';
import 'package:flutter_channel_demo/utils/incomingLink.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_channel_demo/common/Global.dart';

const String appScheme = 'flutterChannelDemo';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true; // 是否开启缓存
  late String _username = '';
  late String _gender = '';
  late List _organizationList;
  late List _sendList = [];
  late int _waitCount = 0;
  bool _loading = false;
  String _selectedOrg = '';
  Uri? _currentURI;
  StreamSubscription? _streamSubscription;

  @override
  void initState() {
    super.initState();
    // 初始化外部跳转到app的监听逻辑
    incomingLinkHandler(_streamSubscription, mounted, (uri) {
      setState(() {
        _currentURI = uri;
      });
    });
    _init();
  }

  _init() async {
    Map info = await getWorkerOrganizations();
    if (info['code'] == 20000) {
      var organs = info['data']['organizations'].map((item) {
        return Organization.fromJson(item);
      }).toList();
      setState(() {
        _organizationList = organs;
      });
      _getWorker();
    }
    _getMyWork();
    _getMyContractsCount();
  }

// 获取个人信息
  Future _getWorker() async {
    var preferences = await SharedPreferences.getInstance();
    var worker = preferences.getString("worker");
    if (worker != null) {
      try {
        var res = Worker.fromJson(json.decode(worker));
        var temp = _organizationList
            .where((element) => element.id == res.organizationId)
            .toList()[0];
        setState(() {
          _username = res.name;
          _gender = res.gender;
          _selectedOrg = temp.organizationName ?? "";
        });
      } catch (e) {
        // debugPrint(e as String?);
        print(e);
        return null;
      }
    }
    return null;
  }

// 获取我的工作列表
  Future _getMyWork() async {
    setState(() {
      _loading = true;
    });
    fetchHomeSend().then((info) {
      if (info['code'] == 20000) {
        List<dynamic> list = info['data']['list'];
        setState(() {
          _sendList = list;
          _loading = false;
        });
      }
    });
  }

  // 获取待签合同数量
  Future _getMyContractsCount() async {
    Map listRes = await fetchContractList(2, 100, 0, "WAITSIGN", context);
    int totalCount = listRes['data']['totalCount'];
    setState(() {
      _waitCount = totalCount;
    });
  }

  @override
  void dispose() {
    _streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (_currentURI != null) {
      navigatePage(context, _currentURI!);
    }
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 0,
      ),
      backgroundColor: const Color(0xfff5f5f5),
      body: ListView(
        children: [
          MyInfo(
            selectedOrg: _selectedOrg,
            username: _username,
            gender: _gender,
            showModalPopup: _showModalPopup,
          ),
          MyContracts(count: _waitCount),
          MyWork(workList: _sendList, loading: _loading)
        ],
      ),
    );
  }

// 显示切换机构的弹窗
  void _showModalPopup(context) {
    showCupertinoModalPopup(
        context: context,
        builder: (context) {
          return CupertinoActionSheet(
              title: const Text(
                '切换企业',
                style: TextStyle(fontSize: 18),
              ),
              actions: _organizationList
                  .map(
                    (item) => CupertinoActionSheetAction(
                      child: Text(item.organizationName),
                      onPressed: () {
                        _changeOrg(context, item);
                      },
                    ),
                  )
                  .toList());
        });
  }

  // 切换机构
  void _changeOrg(BuildContext context, Organization item) async {
    if (_selectedOrg != item.organizationName) {
      setState(() {
        _selectedOrg = item.organizationName;
      });
      Global.worker.token = item.workerId;

      Worker worker;
      var pref = await SharedPreferences.getInstance();
      pref.setString("token", item.workerId);
      var info = await getInfo();
      if (info['code'] == 20000) {
        worker = Worker.fromJson(info['data']);
        Global.worker.id = worker.id;
        print(worker.toJson());
        // 全局存一份
        SharedPreferences.getInstance().then((pre) {
          pre.setString("worker", jsonEncode(worker.toJson()));
        });
        _getMyWork();
        _getMyContractsCount();
      }
    }

    Navigator.pop(context, item);
  }
}
